import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Sign } from './entities/sign.entity';
import { CreateSignDto } from './dto/create-sign.dto';
import { PageQuery } from '../../../util/entity/page.entity';
import { buildQuery } from '../../../util/common-fn';
import { UpdateSignDto } from './dto/update-sign.dto';

@Injectable()
export class SignService {
  constructor(
    @InjectRepository(Sign)
    private signRepository: Repository<Sign>,
  ) {}
  create(createSignDto: CreateSignDto) {
    return this.signRepository.save(createSignDto);
  }

  findAll(pageQuery: PageQuery<Sign>) {
    return this.signRepository.findAndCount(buildQuery(pageQuery));
  }

  findOne(id: number) {
    return this.signRepository.findOneByOrFail({ id });
  }

  update(id: number, updateSignDto: UpdateSignDto) {
    return this.signRepository.update({ id }, updateSignDto);
  }

  remove(id: number) {
    return this.signRepository.softDelete({ id });
  }

  /**
   * 签到
   * @param userId
   */
  async sign(userId: number) {
    // const sign = await this.signRepository
    //   .createQueryBuilder('sign')
    //   .leftJoinAndSelect('sign.user', 'user')
    //   .where('TO_DAYS(sign.createDate) = TO_DAYS(now())')
    //   .andWhere('user.id = :userId', { userId })
    //   .getOne();
    const sign = await this.signRepository
      .createQueryBuilder('sign')
      .where('TO_DAYS(sign.createDate) = TO_DAYS(now())')
      .andWhere('sign.userId = :userId', { userId })
      .getOne();
    if (!sign) {
      await this.signRepository
        .createQueryBuilder()
        .insert()
        .into(Sign)
        .values({ user: { id: userId } })
        .execute();
      return true;
    }
    return false;
  }
}
